﻿using DotNetty.Codecs.Http;
using DotNetty.Common.Utilities;
using DotNetty.Framework;
using DotNetty.Framework.BaseModel;
using System.IO;
using System.Threading.Tasks;

namespace iTool.Connector.HttpWorkers
{
    public class DownloadWorker : IHttpWorker
    {

        public int SecondOfTimeOut { get; set; } = 10;

        public async Task DoWorking<THttpContext>(THttpContext context) where THttpContext : AbstractHttpContext, new()
        {

            await using (FileStream fs = new FileStream("./face.png", FileMode.Open, FileAccess.Read))
            {
                BinaryReader r = new BinaryReader(fs);
                context.ResponseBody = r.ReadBytes((int)fs.Length);
                context.ResponseHeader.Add(new AsciiString("Content-Type"), "image/jpeg");
                //指示下载
                context.ResponseHeader.Add(new AsciiString("Content-Disposition"), "attachment;filename=\"face.png\"");
            }

            context.ResponseStatus = HttpResponseStatus.OK;

        }

        public bool IsUseWorking<THttpContext>(THttpContext context) where THttpContext : AbstractHttpContext, new()
        {
            return context.Path.ToLower() == "/download";
        }

    }
}
